package com.red.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        HttpServletRequest req = (HttpServletRequest) request;
        String currentURL = req.getRequestURI();
        String ctxPath = req.getContextPath();
        //除掉项目名称时访问页面当前路径
        String targetURL = currentURL.substring(ctxPath.length());

        if (req.getSession().getAttribute("user") == null) {
            //对当前页面进行判断，如果当前页面不为登录页面
            if (!("/index.jsp".equals(targetURL))) {
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }
}
